#!/usr/bin/env/python3.7
# -*- coding: utf-8 -*-

"""
@File    : app_ui.py
@Time    : 10/01/2021
@Author  : Silence
@Version : 1.0
@Contact : silence2021silence@163.com
@License : (C)Copyright 2021-2021, Silence
@Desc    : None
"""

import datetime
from PyQt5.QtWidgets import (QMainWindow, QWidget, QTabWidget, QAction, QHBoxLayout,QVBoxLayout,
                             QGridLayout, QLabel, QLCDNumber, QListView, QTableView, QStatusBar,
                             QTextBrowser, QLineEdit, QPushButton, QMessageBox, QRadioButton, QFileDialog)
from PyQt5.QtCore import QRect, QStringListModel, QRegExp, QFile
from PyQt5.QtGui import (QIcon, QStandardItemModel, QStandardItem, QGuiApplication, QRegExpValidator,
                         QDoubleValidator, QIntValidator)
import app_request_mysql
import setting
import app_upload_mysql
import app_read_excel

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(QMainWindow, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        # -----主窗口-----
        self.MAINWINDOW = QWidget()
        self.setCentralWidget(self.MAINWINDOW)
        self.centralWidget = QWidget(self.MAINWINDOW)
        self.setGeometry(self.mainwindow_center_size())

        # -----菜单栏-----
        self.action_1 = QAction("关于程序", self)
        self.action_2 = QAction("关于作者", self)
        self.action_3 = QAction("批量添加学生信息", self)
        self.menubar = self.menuBar()
        self.menubar.setNativeMenuBar(False)
        self.menu_1 = self.menubar.addMenu("关于")
        self.menu_2 = self.menubar.addMenu("添加学生信息")
        self.menu_1.addAction(self.action_1)
        self.menu_1.addAction(self.action_2)
        self.menu_2.addAction(self.action_3)
        self.action_3.triggered.connect(self.action_3_triggered)

        # -----工具栏-----

        # -----状态栏----- #
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar_show()

        # -----主选项卡窗口-----
        self.tabWidget_1 = QTabWidget(self.centralWidget)

        self.tab_1 = QWidget()
        self.tab_2 = QWidget()
        self.tab_3 = QWidget()
        self.tab_4 = QWidget()
        self.tab_5 = QWidget()
        self.tab_6 = QWidget()
        self.tab_14 = QWidget()

        self.tabWidget_1.addTab(self.tab_1, "出勤情况")
        self.tabWidget_1.addTab(self.tab_2, "违纪情况")
        self.tabWidget_1.addTab(self.tab_3, "系统警告")
        self.tabWidget_1.addTab(self.tab_4, "语音留言")
        self.tabWidget_1.addTab(self.tab_5, "设置")
        self.tabWidget_1.addTab(self.tab_6, "系统日志")
        self.tabWidget_1.addTab(self.tab_14, "重要说明")

        self.gridLayout_1 = QGridLayout()
        self.MAINWINDOW.setLayout(self.gridLayout_1)
        self.gridLayout_1.addWidget(self.tabWidget_1)

        # -----出勤情况选项卡窗口-----
        self.tabWidget_2 = QTabWidget(self.tab_1)
        self.tab_7 = QWidget()
        self.tab_8 = QWidget()
        self.tab_9 = QWidget()
        self.tab_10 = QWidget()
        self.tab_11 = QWidget()
        self.tab_12 = QWidget()
        self.tab_13 = QWidget()

        self.tabWidget_2.addTab(self.tab_7, "数据概况")
        self.tabWidget_2.addTab(self.tab_8, "出勤")
        self.tabWidget_2.addTab(self.tab_9, "迟到")
        self.tabWidget_2.addTab(self.tab_10, "缺勤")
        self.tabWidget_2.addTab(self.tab_11, "离开")
        self.tabWidget_2.addTab(self.tab_12, "全部")
        self.tabWidget_2.addTab(self.tab_13, "日志")

        self.gridLayout_2 = QGridLayout()
        self.tab_1.setLayout(self.gridLayout_2)
        self.gridLayout_2.addWidget(self.tabWidget_2)

        # -----数据概况选项卡内容-----
        self.hboxLayout_1 = QHBoxLayout()
        self.gridLayout_3 = QGridLayout()
        self.gridLayout_4 = QGridLayout()
        self.tab_7.setLayout(self.hboxLayout_1)
        self.hboxLayout_1.addLayout(self.gridLayout_3)
        self.hboxLayout_1.addLayout(self.gridLayout_4)

        self.LCDNumber_1 = QLCDNumber()
        self.LCDNumber_2 = QLCDNumber()
        self.LCDNumber_3 = QLCDNumber()
        self.LCDNumber_4 = QLCDNumber()
        self.LCDNumber_5 = QLCDNumber()
        self.LCDNumber_6 = QLCDNumber()
        self.LCDNumber_7 = QLCDNumber()
        self.LCDNumber_8 = QLCDNumber()
        self.LCDNumber_9 = QLCDNumber()
        self.LCDNumber_10 = QLCDNumber()

        self.label_1 = QLabel("总寝室数")
        self.label_2 = QLabel("正常出勤寝室数")
        self.label_3 = QLabel("有迟到情况寝室数")
        self.label_4 = QLabel("有缺勤情况寝室数")
        self.label_5 = QLabel("有中途离开情况寝室数")
        self.label_6 = QLabel("总人数")
        self.label_7 = QLabel("正常出勤人数")
        self.label_8 = QLabel("迟到人数")
        self.label_9 = QLabel("缺勤人数")
        self.label_10 = QLabel("中途离开人数")

        self.gridLayout_3.addWidget(self.label_1)
        self.gridLayout_3.addWidget(self.LCDNumber_1)
        self.gridLayout_3.addWidget(self.label_2)
        self.gridLayout_3.addWidget(self.LCDNumber_2)
        self.gridLayout_3.addWidget(self.label_3)
        self.gridLayout_3.addWidget(self.LCDNumber_3)
        self.gridLayout_3.addWidget(self.label_4)
        self.gridLayout_3.addWidget(self.LCDNumber_4)
        self.gridLayout_3.addWidget(self.label_5)
        self.gridLayout_3.addWidget(self.LCDNumber_5)
        self.gridLayout_4.addWidget(self.label_6)
        self.gridLayout_4.addWidget(self.LCDNumber_6)
        self.gridLayout_4.addWidget(self.label_7)
        self.gridLayout_4.addWidget(self.LCDNumber_7)
        self.gridLayout_4.addWidget(self.label_8)
        self.gridLayout_4.addWidget(self.LCDNumber_8)
        self.gridLayout_4.addWidget(self.label_9)
        self.gridLayout_4.addWidget(self.LCDNumber_9)
        self.gridLayout_4.addWidget(self.label_10)
        self.gridLayout_4.addWidget(self.LCDNumber_10)
        self.tab_7_show()

        # -----出勤选项卡内容-----
        self.vboxLayout_1 = QVBoxLayout()
        self.hboxLayout_2 = QHBoxLayout()
        self.tableView_1 = QTableView()
        self.tableView_1.setSortingEnabled(True)
        self.model = self.table_view(status_= '出勤')
        self.tableView_1.setModel(self.model)
        self.vboxLayout_1.addLayout(self.hboxLayout_2)
        self.vboxLayout_1.addWidget(self.tableView_1)
        self.tab_8.setLayout(self.vboxLayout_1)

        # -----迟到选项卡内容-----
        self.vboxLayout_2 = QVBoxLayout()
        self.hboxLayout_3 = QHBoxLayout()
        self.tableView_2 = QTableView()
        self.tableView_2.setSortingEnabled(True)
        self.model = self.table_view(status_= '迟到')
        self.tableView_2.setModel(self.model)
        self.vboxLayout_2.addLayout(self.hboxLayout_3)
        self.vboxLayout_2.addWidget(self.tableView_2)
        self.tab_9.setLayout(self.vboxLayout_2)

        # -----缺勤选项卡内容-----
        self.vboxLayout_3 = QVBoxLayout()
        self.hboxLayout_4 = QHBoxLayout()
        self.tableView_3 = QTableView()
        self.tableView_3.setSortingEnabled(True)
        self.model = self.table_view(status_= '缺勤')
        self.tableView_3.setModel(self.model)
        self.vboxLayout_3.addLayout(self.hboxLayout_4)
        self.vboxLayout_3.addWidget(self.tableView_3)
        self.tab_10.setLayout(self.vboxLayout_3)

        # -----离开选项卡内容-----
        self.vboxLayout_4 = QVBoxLayout()
        self.hboxLayout_5 = QHBoxLayout()
        self.tableView_4 = QTableView()
        self.tableView_4.setSortingEnabled(True)
        self.model = self.table_view(status_= '离开')
        self.tableView_4.setModel(self.model)
        self.vboxLayout_4.addLayout(self.hboxLayout_5)
        self.vboxLayout_4.addWidget(self.tableView_4)
        self.tab_11.setLayout(self.vboxLayout_4)

        # -----全部选项卡内容-----
        self.vboxLayout_5 = QVBoxLayout()
        self.hboxLayout_6 = QHBoxLayout()
        self.tableView_5 = QTableView()
        self.tableView_5.setSortingEnabled(True)
        self.model = self.table_view(status_= '全部')
        self.tableView_5.setModel(self.model)
        self.vboxLayout_5.addLayout(self.hboxLayout_6)
        self.vboxLayout_5.addWidget(self.tableView_5)
        self.tab_12.setLayout(self.vboxLayout_5)

        # -----违纪选项卡内容----- #

        # -----系统日志选项卡内容----- #
        self.gridLayout_5 = QGridLayout()
        self.textBrowser_1 = QTextBrowser()
        self.gridLayout_5.addWidget(self.textBrowser_1)
        self.tab_6.setLayout(self.gridLayout_5)
        self.textBrowser_1_show()

        # -----日志选项卡内容----- #
        self.gridLayout_6 = QGridLayout()
        self.textBrowser_2 = QTextBrowser()
        self.gridLayout_6.addWidget(self.textBrowser_2)
        self.tab_13.setLayout(self.gridLayout_6)
        self.textBrowser_2_show()

        # -----语音留言选项卡内容----- #
        self.vboxLayout_7 = QVBoxLayout()
        self.listView_7 = QListView()
        self.stringListModel_7 = QStringListModel()
        self.vboxLayout_7.addWidget(self.listView_7)
        self.tab_4.setLayout(self.vboxLayout_7)
        self.sql_data_23 = app_request_mysql.Data.data_23()
        self.stringListModel_7.setStringList(self.sql_data_23)
        self.listView_7.setModel(self.stringListModel_7)
        self.listView_7.clicked.connect(self.listView_7_clicked)

        # -----设置选项卡内容----- #
        self.vboxLayout_8 = QVBoxLayout()
        self.label_11 = QLabel("开放考勤时间(晚于此时间系统将开放考勤)")
        self.label_12 = QLabel("考勤迟到时间(早于此时间系统将记为正常出勤)")
        self.label_13 = QLabel("离开超时时间(离开时间大于此时间系统将记录为离开)")
        self.label_14 = QLabel("人体红外传感器最小值(大于此值系统将记为正常出勤)")
        self.label_15 = QLabel("体温最小值(大于此值系统将记为正常出勤)")
        self.label_16 = QLabel("体温最大值(小于此值系统将记为正常出勤)")
        self.label_17 = QLabel("体重最小值(大于此值系统将记为正常出勤)")
        self.label_18 = QLabel("体重最大值(小于此值系统将记为正常出勤)")
        self.label_19 = QLabel("噪音最大值(小于此值系统将记为遵守纪律)")
        self.label_20 = QLabel("烟雾传感器开关状态(0为关，1为开，开启状态系统将记为无有害气体)")
        self.label_21 = QLabel("烟雾浓度最大值(小于此值系统将记为无有害气体)")

        (open_datetime, late_datetime, leaving_timeout, infrared_value, temperature_value_min,
         temperature_value_max, weight_value_min, weight_value_max, volume_value_max, smoke_ttl,
         smoke_value_max) = setting.Setting.read_setting()

        self.lineEdit_1 = QLineEdit(str(open_datetime))
        self.lineEdit_2 = QLineEdit(str(late_datetime))
        self.lineEdit_3 = QLineEdit(leaving_timeout)
        self.lineEdit_4 = QLineEdit(infrared_value)
        self.lineEdit_5 = QLineEdit(temperature_value_min)
        self.lineEdit_6 = QLineEdit(temperature_value_max)
        self.lineEdit_7 = QLineEdit(weight_value_min)
        self.lineEdit_8 = QLineEdit(weight_value_max)
        self.lineEdit_9 = QLineEdit(volume_value_max)
        self.lineEdit_10 = QLineEdit(smoke_ttl)
        self.lineEdit_11 = QLineEdit(smoke_value_max)

        self.regExpValidator_1 = QRegExpValidator()
        self.regExpValidator_2 = QRegExpValidator()
        self.doubleValidator_1 = QDoubleValidator()
        self.intValidator_1 = QIntValidator()
        self.intValidator_2 = QIntValidator()
        self.intValidator_3 = QIntValidator()
        self.regExp_1 =QRegExp('[0-9]+-+[0-9]+-+[0-9]+[ ]+[0-9]+:+[0-9]+:+[0-9]+[0-9]')
        self.regExp_2 = QRegExp('[0-1]')

        self.regExpValidator_1.setRegExp(self.regExp_1)
        self.regExpValidator_2.setRegExp(self.regExp_2)
        self.doubleValidator_1.setRange(35, 40)
        self.doubleValidator_1.setNotation(QDoubleValidator.StandardNotation)
        self.doubleValidator_1.setDecimals(1)
        self.intValidator_1.setRange(40, 90)
        self.intValidator_2.setRange(10, 200)
        self.intValidator_3.setRange(0, 500)

        self.lineEdit_1.setValidator(self.regExpValidator_1)
        self.lineEdit_2.setValidator(self.regExpValidator_1)
        self.lineEdit_4.setValidator(self.intValidator_3)
        self.lineEdit_5.setValidator(self.doubleValidator_1)
        self.lineEdit_6.setValidator(self.doubleValidator_1)
        self.lineEdit_7.setValidator(self.intValidator_1)
        self.lineEdit_8.setValidator(self.intValidator_1)
        self.lineEdit_9.setValidator(self.intValidator_2)
        self.lineEdit_10.setValidator(self.regExpValidator_2)
        self.lineEdit_11.setValidator(self.intValidator_3)

        self.pushButton_1 = QPushButton()
        self.pushButton_1.setText('提交')

        self.vboxLayout_8.addWidget(self.label_11)
        self.vboxLayout_8.addWidget(self.lineEdit_1)
        self.vboxLayout_8.addWidget(self.label_12)
        self.vboxLayout_8.addWidget(self.lineEdit_2)
        self.vboxLayout_8.addWidget(self.label_13)
        self.vboxLayout_8.addWidget(self.lineEdit_3)
        self.vboxLayout_8.addWidget(self.label_14)
        self.vboxLayout_8.addWidget(self.lineEdit_4)
        self.vboxLayout_8.addWidget(self.label_15)
        self.vboxLayout_8.addWidget(self.lineEdit_5)
        self.vboxLayout_8.addWidget(self.label_16)
        self.vboxLayout_8.addWidget(self.lineEdit_6)
        self.vboxLayout_8.addWidget(self.label_17)
        self.vboxLayout_8.addWidget(self.lineEdit_7)
        self.vboxLayout_8.addWidget(self.label_18)
        self.vboxLayout_8.addWidget(self.lineEdit_8)
        self.vboxLayout_8.addWidget(self.label_19)
        self.vboxLayout_8.addWidget(self.lineEdit_9)
        self.vboxLayout_8.addWidget(self.label_20)
        self.vboxLayout_8.addWidget(self.lineEdit_10)
        self.vboxLayout_8.addWidget(self.label_21)
        self.vboxLayout_8.addWidget(self.lineEdit_11)
        self.vboxLayout_8.addWidget(self.pushButton_1)

        self.tab_5.setLayout(self.vboxLayout_8)
        self.pushButton_1.clicked.connect(self.pushButton_1_clicked)

    # -----重要说明选项卡内容----- #
        self.vboxLayout_9 = QVBoxLayout()
        self.label_20 = QLabel()
        self.label_20.setText('(在此时间后床位上无人，则系统视其为缺席；'
                              '在此时间后考勤的学生，则系统视其为迟到；'
                              '在此时间后出勤学生离开床位，则系统视其为离开)')
        self.vboxLayout_9.addWidget(self.label_20)
        self.tab_14.setLayout(self.vboxLayout_9)

    def mainwindow_center_size(self):
        screen_size = QGuiApplication.primaryScreen()
        screen_width = screen_size.geometry().width()
        screen_height = screen_size.geometry().height()
        mainwindow_width = screen_width // 4 * 3
        mainwindow_height = screen_height // 4 * 3
        mainwindow_x = screen_width // 2 - mainwindow_width // 2
        mainwindow_y = screen_height // 2 - mainwindow_height // 2
        return QRect(mainwindow_x, mainwindow_y, mainwindow_width, mainwindow_height)

    # 数据总览
    def tab_7_show(self):
        self.LCDNumber_1.display(int(app_request_mysql.Data.data_overview(type_1='room',type_2='all')))
        self.LCDNumber_2.display(int(app_request_mysql.Data.data_overview(type_1='room',type_2='出勤')))
        self.LCDNumber_3.display(int(app_request_mysql.Data.data_overview(type_1='room',type_2='迟到')))
        self.LCDNumber_4.display(int(app_request_mysql.Data.data_overview(type_1='room',type_2='缺勤')))
        self.LCDNumber_5.display(int(app_request_mysql.Data.data_overview(type_1='room',type_2='离开')))
        self.LCDNumber_6.display(int(app_request_mysql.Data.data_overview(type_1='student_number',type_2='all')))
        self.LCDNumber_7.display(int(app_request_mysql.Data.data_overview(type_1='student_number',type_2='出勤')))
        self.LCDNumber_8.display(int(app_request_mysql.Data.data_overview(type_1='student_number',type_2='迟到')))
        self.LCDNumber_9.display(int(app_request_mysql.Data.data_overview(type_1='student_number',type_2='缺勤')))
        self.LCDNumber_10.display(int(app_request_mysql.Data.data_overview(type_1='student_number',type_2='离开')))

    # -----状态栏----- #
    def statusBar_show(self):
        if app_request_mysql.database:
            self.statusBar.showMessage('Connect Database Successful On ' +
                                       str(datetime.datetime.now().replace(microsecond=0)))

    # -----系统日志----- #
    def textBrowser_1_show(self):
        if app_request_mysql.database:
            self.textBrowser_1.setPlainText(str(datetime.datetime.now().replace(microsecond=0)) + ' '
                                            + 'Connect Database Successful !')

    def textBrowser_2_show(self):
        if app_request_mysql.database:
            self.textBrowser_2.setPlainText(str(datetime.datetime.now().replace(microsecond=0)) + ' '
                                            + 'Connect Database Successful !')


    def listView_7_clicked(self, QModelIndex):
        self.SelectedSpeaker = self.sql_data_23[QModelIndex.row()]
        app_request_mysql.Data.data_24(clicked_speaker_id=self.SelectedSpeaker[4:6],
                                   clicked_speaker_name=self.SelectedSpeaker[18:])

    def table_view(self, status_):
        (id, student_number, name, room, grade, class_, ip_address,
         status, status_datetime) = app_request_mysql.Data.data_16(status=status_)
        model = QStandardItemModel(len(id), 9)
        model.setHorizontalHeaderLabels(['id', '学号', '姓名', '寝室号', '年级', '班别',
                                                'IP地址', '状态', '状态开始时间'])
        for row in range(len(id)):
            Item0 = QStandardItem('%s' % id[row])
            Item1 = QStandardItem('%s' % student_number[row])
            Item2 = QStandardItem('%s' % name[row])
            Item3 = QStandardItem('%s' % room[row])
            Item4 = QStandardItem('%s' % grade[row])
            Item5 = QStandardItem('%s' % class_[row])
            Item6 = QStandardItem('%s' % ip_address[row])
            Item7 = QStandardItem('%s' % status[row])
            Item8 = QStandardItem('%s' % status_datetime[row])
            for column in range(len(id)):
                model.setItem(row, 0, Item0)
                model.setItem(row, 1, Item1)
                model.setItem(row, 2, Item2)
                model.setItem(row, 3, Item3)
                model.setItem(row, 4, Item4)
                model.setItem(row, 5, Item5)
                model.setItem(row, 6, Item6)
                model.setItem(row, 7, Item7)
                model.setItem(row, 8, Item8)
        return model

    def pushButton_1_clicked(self):
        if self.lineEdit_1.text() == '' \
        or self.lineEdit_2.text() == '' \
        or self.lineEdit_3.text() == '' \
        or self.lineEdit_4.text() == '' \
        or self.lineEdit_5.text() == '' \
        or self.lineEdit_6.text() == '' \
        or self.lineEdit_7.text() == '' \
        or self.lineEdit_8.text() == '' \
        or self.lineEdit_9.text() == ''\
        or self.lineEdit_10.text() == ''\
        or self.lineEdit_11.text() == '':
            QMessageBox.warning(self, '警告', '所有参数不能为空', QMessageBox.Ok)
        else:
            setting.Setting.setting(self.lineEdit_1.text(), self.lineEdit_2.text(), self.lineEdit_3.text(),
                            self.lineEdit_4.text(), self.lineEdit_5.text(), self.lineEdit_6.text(),
                            self.lineEdit_7.text(), self.lineEdit_8.text(), self.lineEdit_9.text(),
                            self.lineEdit_10.text(), self.lineEdit_11.text())
            QMessageBox.information(self, '信息', '设置修改成功', QMessageBox.Ok)

    def action_3_triggered(self):
        file_path, file_type = QFileDialog.getOpenFileName(self, '选择文件', './', 'Excel Files (*.xls)')
        list = app_read_excel.ReadExcel.read_excel(excel_path=file_path)
        upload = app_upload_mysql.UploadMySQL.upload_student_info(student_info_list=list)
        if upload == 'success':
            QMessageBox.information(self, '信息', '学生信息上传成功', QMessageBox.Ok)
        else:
            QMessageBox.warning(self, '信息', '学生信息上传失败', QMessageBox.Ok)
